package org.zh.home.dao.impl;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import org.zh.home.dao.BaseDao;
import org.zh.home.dao.IRoleDao;
import org.zh.home.entity.Role;
import org.zh.home.entity.User;
import org.zh.home.model.Pager;
import org.zh.home.model.Param;
import org.zh.home.model.Query;
import org.zh.home.utils.QueryUtils;

@Repository
public class RoleDao extends BaseDao<Role> implements IRoleDao {

	@Override
	public Pager<Role> find(List<Query> model) {
		Param param = QueryUtils.generateHQLBase("from Role", "r", model);
		return super.find(param.getQuery(), param.getValues().toArray());
	}
	
	@Override
	public List<Role> list(List<Query> model) {
		Param param = QueryUtils.generateHQLBase("from Role", "r", model);
		return super.list(param.getQuery(), param.getValues().toArray());
	}


	@Override
	public List<User> listUserByRole(int roleId) {
		String sql = "select u.* from sdf_user u join sdf_user_role r on(u.id=r.user_id) where r.role_id = "+roleId;
		return super.listBySql(sql, User.class, true);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Integer> listUserIdsByRole(int roleId) {
		String sql = "select ur.user_id from sdf_user_role ur where ur.role_id = "+roleId;
		Session session = super.getSession();
		SQLQuery query = session.createSQLQuery(sql);
		return query.list();
	}

	@Override
	public void deleteRoleResource(int id) {
		String hql = "delete RoleResource rr where rr.roleId = "+id;
		super.updateByHql(hql);
	}

	@Override
	public void updateUserGroupRole(int id) {
		String hql = "update UserGroupRole ugr set ugr.roleId = 0,ugr.roleName = '' where ugr.roleId = "+id;
		super.updateByHql(hql);
	}
}
